import { useEffect, useState } from "react";
import { GetGoods, DelGoods, BanGoods, ShelveGoods, Addlneve } from "../../api/commodity";
import { Button, Input, Space, Table, Image, Tag, message, Checkbox, Spin, Modal, InputNumber, Pagination,Skeleton } from "antd"
import { useNavigate } from 'react-router-dom';
import "../../css/order.css"

import React from 'react';
const PAGE_SIZE = 5;// 设置每页显示的数据条数
const Goods = () => {
    const navigate = useNavigate()
    const [isDirectly, setIsDirectly] = useState(-1);
    const [isBan, setIsBan] = useState(-1);
    const [isShelve, setIsShelve] = useState(-1);
    const [inventory, setInVentory] = useState(-1);
    const [loading, setLoading] = React.useState(false);
    const [currentPage, setCurrentPage] = useState(1);//当前页
    const [total, setTotal] = useState(0); // 定义total变量
    const [searchKeyword, setSearchKeyword] = useState('');//搜索关键字
    const [shows, setShows] = useState(true);//骨架屏

    // 获取商品列表
    const [goods, setGoods] = useState([]);
    const [number, setNumber] = useState([]);
    const [id, setId] = useState([]);

    const [visible, setVisible] = useState(false); // 控制模态框的显示与隐藏  

    const showModal = (record) => {
        setVisible(true); // 显示模态框  
        setId(record.id)
    };

    const handleOk = () => {
        setLoading(true)
        Addlneve({
            id: id,
            number: number
        }).then((res) => {
            if (res.result === 0) {
                setLoading(false)
                message.success(res.message);
                bindgoods();
            } else {
                setLoading(false)
                message.error(res.message)
            }
        });

        // 处理模态框确定按钮的点击事件  
        setVisible(false); // 隐藏模态框  
    };

    const handleCancel = () => {
        // 处理模态框取消按钮的点击事件  
        setVisible(false); // 隐藏模态框  
    };

    const handlePageChange = (page) => {
        setCurrentPage(page);
    };

    const bindgoods = () => {
        setLoading(true)
        GetGoods({
            page: currentPage,
            limit: PAGE_SIZE,
            isBan: isBan,
            isShelve: isShelve,
            inventory: -1,
            isDirectly: isDirectly,
            key: searchKeyword,
            // total:''
        }).then((res) => {
            if (res.result === 0) {
                setLoading(false)
                setGoods(res.data.data);
                setTotal(res.data.total);
                setShows(false);
            }
        })
    }

    useEffect(() => {
        bindgoods();
    }, [isDirectly, isBan, isShelve, inventory, currentPage, searchKeyword])

    const handleNumberChange = (value) => {
        setNumber(value);
    };

    const check = (val) => {
        for (let i = 0; i < val.length; i++) {
            if (val[i] === 1) {
                setIsDirectly(1);
            };
            if (val[i] !== 1) {
                setIsDirectly(-1);
            };
            if (val[i] === 2) {
                setIsBan(1);
            };
            if (val[i] !== 2) {
                setIsBan(-1);
            };
            if (val[i] === 3) {
                setIsShelve(1);
            };
            if (val[i] !== 3) {
                setIsShelve(-1);
            };
            if (val[i] === 4) {
                setInVentory(1);
            };
            if (val[i] !== 4) {
                setInVentory(-1);
            };
        };
        if (val.length === 0) {
            setIsDirectly(-1);
            setIsBan(-1);
            setIsShelve(-1);
            setInVentory(-1);
        }
        bindgoods();
    }

    // 获取商品列表(表格)
    const good = [
        {
            title: "序号",
            render: (text, record, index) => `${index + 1}`,
            width: 65
        },
        {
            title: '图片',
            dataIndex: 'photo',
            // ellipsis: true,
            width: 100,
            render: (text) => (
                <Image
                    width={40}
                    src={text}
                />
            )
        },
        {
            title: '名称',
            dataIndex: 'name',
            key: 'merchant',
            ellipsis: true,
            width: 90
        },
        {
            title: '供应商',
            dataIndex: 'supplier',
            key: 'supplier',
            width: 135,
            ellipsis: true,
            render: (_, record) => (
                <>
                    <Tag color={record.supplier == null ? "error" : "blue"} > {record.supplier === null ? '自营' : record.supplier}</Tag>
                </>
            ),
        },
        {
            title: '单价',
            dataIndex: 'price',
            ellipsis: true,
            width: 100,
            render: (val, i) => (
                <>
                    <Tag color="error" key={i.id}>￥{val}</Tag>
                </>
            )
        },
        {
            title: '库存总数',
            dataIndex: 'inventory',
            width: 90,
            render: (_, record) => (
                <>
                    <Tag color="processing">{record.inventory}</Tag>
                </>
            )
        },
        {
            title: '销量',
            dataIndex: 'sales',
            // ellipsis: true,
            width: 65,
            render: (val, i) => (
                <>
                    <Tag color="processing" key={i.id}>{val}</Tag>
                </>
            )
        },
        {
            title: '生产日期',
            dataIndex: 'birthday',
            width: '90px',
            ellipsis: true,
        },
        {
            title: '保质期',
            dataIndex: 'expiryday',
            width: '80px',
            render: (val, i) => (
                <>
                    <Tag color="blue">{val}</Tag>
                </>
            )
        },
        {
            title: '剩余天数',
            dataIndex: 'surplus',
            // ellipsis: true,
            width: '90px',
            render: (val, i) => (
                <>
                    <Tag color="green" key={i.id}>{val}</Tag>
                </>
            )
        },
        // {
        //     title: '上架时间',
        //     dataIndex: 'shelveTime',
        //     width: '90px',
        //     ellipsis: true,
        // },
        {
            title: '上架',
            dataIndex: 'isShelve',
            width: 65,
            render: (_, val) => {
                return <Tag color={val.isShelve === 0 ? "orange" : "green"}> {val.isShelve === 0 ? "否" : "是"}</Tag>
            }
        },
        {
            title: '禁用',
            dataIndex: 'isBan',
            render: (_, val) => {
                return <Tag color={val.isBan === 0 ? "green" : "error"}> {val.isBan === 0 ? "否" : "是"}</Tag>
            }
        },

        {
            title: '操作',
            dataIndex: 'address',
            width: 250,
            render: (_, record) => {
                if (record.isShelve === 0 && record.isBan === 0 && record.sales === 0 && record.inventory === 0) {
                    return <span>
                        <button

                            onClick={() => {
                                console.log(record.id)
                                navigate("/goods/detail/" + record.id)
                            }}
                            className="el-tag-info ">详情</button>
                        <button className="el-tag-zi ma-b" ghost size='small'>资质</button>
                        <button
                            onClick={() => {
                                setLoading(true);
                                DelGoods({
                                    id: record.id
                                }).then((res) => {
                                    if (res.result === 0) {
                                        setLoading(false)
                                        console.log(111);
                                        message.success(res.message);
                                        bindgoods();
                                    } else {
                                        message.error(res.message);
                                    }
                                })
                            }}
                            className="el-tag-del ma-b" ghost size='small'>删除</button>
                    </span>
                } else {
                    return <span>

                        <button
                            onClick={() => {
                                console.log(record.id)
                                navigate("/goods/detail/" + record.id)
                            }}
                            className="el-tag-info ">详情</button>
                        <button className="el-tag-zi ma-b" ghost size='small'>资质</button>
                        {/* 下架商品  */}
                        {record.isShelve === 1 && record.isBan === 0 && (<button
                            onClick={() => {
                                setLoading(true)
                                ShelveGoods({
                                    ids: [record.id],
                                    isShelve: 0
                                }).then((res) => {
                                    if (res.result === 0) {
                                        setLoading(false)
                                        message.success(res.message);
                                        bindgoods();
                                    } else {
                                        message.error(res.message);
                                    }
                                })
                            }}
                            className="el-tag-xia ma-b" size='small' ghost block>下架</button>)}
                        {/* 上架商品 */}
                        {record.isShelve === 0 && record.inventory !== 0 && record.isBan === 0 && (<button
                            onClick={() => {
                                setLoading(true)
                                ShelveGoods({
                                    ids: [record.id],
                                    isShelve: 1
                                }).then((res) => {
                                    if (res.result === 0) {
                                        setLoading(false)
                                        message.success(res.message);
                                        bindgoods();
                                    } else {
                                        message.error(res.message);
                                    }
                                })
                            }}
                            className="el-tag-shang ma-b" ghost size='small'>上架</button>)}
                        {/* 禁用商品 */}
                        {record.isBan === 0 && (<button
                            onClick={() => {
                                setLoading(true)
                                BanGoods({
                                    ids: [record.id],
                                    isBan: 1
                                }).then((res) => {
                                    if (res.result === 0) {
                                        setLoading(false)
                                        message.success(res.message);
                                        bindgoods();
                                    } else {
                                        message.error(res.message);
                                    }
                                })
                            }}
                            className="el-tag-ban ma-b" ghost size='small'>禁用</button>)}
                        {/* 启用商品 */}
                        {record.isBan === 1 && (<button
                            onClick={() => {
                                setLoading(true)
                                BanGoods({
                                    ids: [record.id],
                                    isBan: 0
                                }).then((res) => {
                                    if (res.result === 0) {
                                        setLoading(false)
                                        message.success(res.message);
                                        bindgoods();
                                    } else {
                                        message.error(res.message);
                                    }
                                })
                            }}
                            className="el-tag-shang ma-b" ghost size='small'>启用</button>)}
                        {/* 补货 */}
                        {record.isDirectly === 1 && ( // 如果record.isDirectly等于1，则显示按钮  
                            <Button type="primary" className="el-tag-zi ma-b" ghost size='small' onClick={() => showModal(record)} >
                                补货
                            </Button>
                        )}
                        <Modal
                            title="补货"
                            visible={visible} // 控制模态框的显示与隐藏  
                            onOk={handleOk}
                            onCancel={handleCancel}
                            okText="补货" // 设置确定按钮的文本为“确定”  
                            cancelText="取消" // 设置取消按钮的文本为“取消”
                            mask={false}
                        >
                            <p><InputNumber min={100} max={2000} onChange={handleNumberChange} defaultValue={0} style={{ width: '100%', }} />,</p>
                        </Modal>

                    </span>
                }
            }
        },
    ];

    return (
        <div className="exam-container">
            <Skeleton loading={shows} active={true} paragraph={{ rows: 10 }} rows={20} style={{ padding: '10px' }}>
                <Spin spinning={loading} delay={500}>
                    <div className="">
                        <div className="">
                            <div className="button">
                                <div className="box-button1">
                                    <Button type="primary" id='button-xq' onClick={() => {
                                        navigate('/goods/add')
                                    }}>新增商品</Button>
                                </div>
                                <div className='box-button2'>
                                    <Space.Compact style={{ width: '100%', height: '40px' }}>
                                        <Input placeholder="输入商品名搜索" value={searchKeyword}
                                            onChange={(e) => setSearchKeyword(e.target.value)} ></Input>
                                        <Button type="primary" ghost style={{ height: '40px' }}>搜索</Button>
                                    </Space.Compact>
                                </div>
                                <div>
                                    <Checkbox.Group onChange={check}>
                                        <Checkbox className="check" value={1}>自营</Checkbox>
                                        <Checkbox className="check" value={2}>禁用</Checkbox>
                                        <Checkbox className="check" value={3}>上架</Checkbox>
                                        <Checkbox className="check" value={4}>库存</Checkbox>
                                    </Checkbox.Group>
                                </div>
                            </div>

                            <Table
                                columns={good}
                                dataSource={goods}
                                bordered
                                pagination={false}
                                scroll={{
                                    x: 1300,
                                }}
                            />

                            <Pagination current={currentPage} total={total} pageSize={PAGE_SIZE} onChange={handlePageChange} className="pagination" />
                        </div>
                    </div>
                </Spin>
            </Skeleton>
        </div>
    )
}

export default Goods


